package com.hhkj.study.api.goods.service.biz.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hhkj.study.admin.course.entity.Course;
import com.hhkj.study.admin.course.entity.CourseAssocResourceStat;
import com.hhkj.study.admin.course.enums.CourseAssocResourceTypeEnum;
import com.hhkj.study.admin.course.service.base.CourseService;
import com.hhkj.study.admin.course.service.extend.CourseExtendService;
import com.hhkj.study.admin.goods.model.podo.GoodsSkuPo;
import com.hhkj.study.admin.goods.model.req.GoodsSkuReq;
import com.hhkj.study.admin.goods.model.res.GoodsRes;
import com.hhkj.study.admin.goods.model.res.GoodsSkuRes;
import com.hhkj.study.admin.goods.service.biz.GoodsBizService;
import com.hhkj.study.admin.goods.service.biz.GoodsSkuBizService;
import com.hhkj.study.api.goods.model.res.ApiGoodsRes;
import com.hhkj.study.api.goods.service.biz.ApiGoodsBizService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author luowu
 * @Date 2024/10/9 涵 13:48:22
 */
@Slf4j
@Service
public class ApiGoodsBizServiceImpl implements ApiGoodsBizService {

    @Resource
    private GoodsBizService goodsBizService;

    @Resource
    private GoodsSkuBizService goodsSkuBizService;

    @Resource
    private CourseService courseService;

    @Resource
    private CourseExtendService courseExtendService;

    @Override
    public ApiGoodsRes getGoodsDetailById(Long goodsId) {
        // 1.获取商品基本信息
        GoodsRes goodsRes = goodsBizService.getById(goodsId);
        // 处理商品下的课程数
        afterHandlerCourse(goodsRes);
        return BeanUtil.toBean(goodsRes, ApiGoodsRes.class);
    }


    @Override
    public Map<Long, List<Course>> getCourseListByGoodIdList(List<Long> goodsIdList) {
        Pair<List<GoodsSkuRes>, List<Course>> goodsSkuAndCourseListPair = getGoodsSkuAndCourseList(goodsIdList);
        if (ObjectUtil.isNull(goodsSkuAndCourseListPair)) {
            return Maps.newHashMap();
        }
        Map<Long, Set<Long>> goodsIdCourseIdListMap = goodsSkuAndCourseListPair.getLeft().stream().collect(Collectors.groupingBy(
                        GoodsSkuRes::getGoodsId,
                        Collectors.mapping(
                                GoodsSkuRes::getCourseIdList,
                                Collectors.toSet())))
                .entrySet()
                .stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> entry.getValue().stream()
                                .flatMap(Collection::stream)
                                .collect(Collectors.toSet())));
        // 该商品下所有的课程
        List<Course> courseList = goodsSkuAndCourseListPair.getRight();
        Map<Long, List<Course>> goodIdCourseListMap = Maps.newHashMap();
        goodsIdCourseIdListMap.forEach((goodId, courseIdSet) -> {
            List<Course> coursePartitionList = courseExtendService.getCourseResList(Lists.newArrayList(courseIdSet), courseList);
            if (CollectionUtil.isNotEmpty(coursePartitionList)) {
                goodIdCourseListMap.put(goodId, coursePartitionList);
            }
        });
        // 所有上架的课程得到课程相关结构
        return goodIdCourseListMap;
    }

    /**
     * 商品id列表获取商品sku列表和课程列表
     * @param goodsIdList
     * @return
     */
    private Pair<List<GoodsSkuRes>, List<Course>> getGoodsSkuAndCourseList(List<Long> goodsIdList) {
        if (CollectionUtil.isEmpty(goodsIdList)) {
            return null;
        }
        GoodsSkuReq goodsSkuReq = new GoodsSkuReq();
        goodsSkuReq.setGoodsIdList(goodsIdList);
        List<GoodsSkuRes> goodsSkuResList = goodsSkuBizService.list(goodsSkuReq);
        if (CollectionUtil.isEmpty(goodsSkuResList)) {
            return null;
        }
        // 商品sku中所有的课程id
        Set<Long> goodsSkuCourseIdSet = goodsSkuResList.stream().filter(e -> CollectionUtil.isNotEmpty(e.getCourseIdList()))
                .flatMap(goodsSku -> goodsSku.getCourseIdList().stream()).collect(Collectors.toSet());
        if (CollectionUtil.isEmpty(goodsSkuCourseIdSet)) {
            return null;
        }
        List<Course> courseList = courseService.listByIds(goodsSkuCourseIdSet);
        return Pair.of(goodsSkuResList, courseList);
    }

    /**
     * 计算该商品下课程视频数
     * @param goodsRes
     */
    private void afterHandlerCourse(GoodsRes goodsRes) {
        try {
            if (ObjectUtil.isNull(goodsRes) || CollectionUtil.isEmpty(goodsRes.getSkuList())) {
                return;
            }
            Set<Long> courseIdList = goodsRes.getSkuList().stream().filter(e -> ObjectUtil.isNotNull(e) && CollectionUtil.isNotEmpty(e.getCourseIdList())).flatMap(e -> e.getCourseIdList().stream()).collect(Collectors.toSet());
            if (CollectionUtil.isEmpty(courseIdList)) {
                return;
            }
            List<Course> courseList = courseExtendService.listByIdList(courseIdList);
            List<CourseAssocResourceStat> resourceStatList = courseList.stream()
                    .filter(e -> ObjectUtil.isNotNull(e) && ObjectUtil.isNotNull(e.getAssocResourceStat()) && CollectionUtil.isNotEmpty(e.getAssocResourceStat().getCourseAssocResourceList()))
                    .flatMap(e -> e.getAssocResourceStat().getCourseAssocResourceList().stream()).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(resourceStatList)) {
                Integer lessonCount = resourceStatList.stream().filter(e -> CourseAssocResourceTypeEnum.VIDEO.getCode().equals(e.getResourceType())).map(CourseAssocResourceStat::getResourceCount).reduce(0, Integer::sum);
                goodsRes.setLessonCount(lessonCount);
            }
        } catch (Exception e) {
            log.error("该商品下计算课时数出错,商品id为{}", goodsRes.getId(), e);
        }
    }
}
